﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Sami_SMS_CRM_Business;
using Settings;
using System.Web.UI.HtmlControls;
using Utils;
using System.Web.Services;

namespace Sami_SMS_CRM_UI
{
    public partial class crm_advertisment : BasePage
    {
        AdvertismentRepository repository = new AdvertismentRepository();
        CollectionRepository collectionRepository = new CollectionRepository();
        
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            if (!AllowManageAdvertisment())
            {
                RedirectToPage(AccessDeniedURL);
            }
            pagingtop.PagingChange += new EventHandler(paging_PagingChange);
            pagingbottom.PagingChange += new EventHandler(paging_PagingChange);
        }

        void paging_PagingChange(object sender, EventArgs e)
        {
            pagingtop.PagingChange -= new EventHandler(paging_PagingChange);
            pagingbottom.PagingChange -= new EventHandler(paging_PagingChange);
            pagingtop.CurrentPage = (sender as UserControl.ucPaging).CurrentPage;
            pagingbottom.CurrentPage = (sender as UserControl.ucPaging).CurrentPage;
            BindDataTable();
            pagingtop.Visible = (sender as UserControl.ucPaging).TotalPage > 1;
            pagingtop.PagingChange += new EventHandler(paging_PagingChange);
            pagingbottom.Visible = (sender as UserControl.ucPaging).TotalPage > 1;
            pagingbottom.PagingChange += new EventHandler(paging_PagingChange);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                PageSize = Convert.ToInt32(ddlPageSize.SelectedValue);
                pagingtop.CurrentPage = 1;
                pagingtop.PageSize = PageSize;
                pagingtop.PageDisplay = PageDisPlay;
                pagingbottom.CurrentPage = 1;
                pagingbottom.PageSize = PageSize;
                pagingbottom.PageDisplay = PageDisPlay;
                BindDataTable();
            }
        }

        private void BindDataTable()
        {
            int currentPage = pagingtop.CurrentPage;
            int pageSize = pagingtop.PageSize;
            int totalRecord = 0;

            rptTable.DataSource = repository.GetAll(currentPage, pageSize, ref totalRecord);
            rptTable.DataBind();

            pagingtop.TotalRecord = totalRecord;
            pagingtop.Visible = pagingtop.TotalPage > 1;
            pagingbottom.TotalRecord = totalRecord;
            pagingbottom.Visible = pagingtop.TotalPage > 1;
            ltrTotalRow.Text = totalRecord.ToString();
        }

        protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            pagingtop.PageSize = pagingbottom.PageSize = int.Parse((sender as DropDownList).SelectedValue);
            BindDataTable(); 
        }

        protected void rptTable_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            try
            {
                if (IsAdmin())
                {
                    int id = Convert.ToInt32(e.CommandArgument);
                    switch (e.CommandName)
                    {
                        case "Edited":
                            var entity = repository.GetById(id);
                            SetDataAdv(entity);
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "", "OpenDialog('dialog-form1');", true);
                            break;
                        case "Deleted":
                            repository.DeleleById(id);
                            BindDataTable();
                            break;
                    }
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert(\"You don't have permission!\");", true);
                }
            }
            catch (Exception ex)
            {
                new LogRepository().InsertLog(ex);
            }
        }

        private void SetDataAdv(Sami_SMS_CRM_Business.crm_advertisment entity)
        {
            if (ddlStatus.Items.Count == 0)
            {
                foreach (var item in typeof(Status).GetFields())
                {
                    ddlStatus.Items.Add(new ListItem(item.Name, item.GetRawConstantValue().ToString()));
                }
            }
            if (ddlAction.Items.Count == 0)
            {
                foreach (var item in new ActionRepository().GetAll())
                {
                    ddlAction.Items.Add(new ListItem(item.action_name, item.action_id.ToString()));
                }
            }
            if (ddlSenderName.Items.Count == 0)
            {
                foreach (var item in new SenderNameRepository().GetAll())
                {
                    ddlSenderName.Items.Add(new ListItem(item.sender_name, item.sender_name));
                }
            }
            if (ddlMtFlag.Items.Count == 0)
            {
                foreach (var item in new MtFlagRepository().GetAll())
                {
                    ddlMtFlag.Items.Add(new ListItem(item.mt_flag, item.mt_flag));
                }
            }

            if (ddlCollection.Items.Count == 0)
            {
                foreach (var item in new CollectionRepository().GetAll())
                {
                    ddlCollection.Items.Add(new ListItem(item.collection_name, item.collection_id.ToString()));
                }
            }

            if (entity != null)
            {
                hdfAction.Value = "Edit";
                hdfAdvId.Value = entity.advertisment_id.ToString();
                txtMessage.Text = entity.message;
                ddlSenderName.SelectedValue = entity.sender_name;
                ddlMtFlag.SelectedValue = entity.mt_flag;
                txtStartExpected.Text = entity.start_expected.ToString();
                txtEndExpected.Text = entity.end_expected.ToString();
                txtSentFrom.Text = entity.allow_sent_from.ToString();
                txtSentTo.Text = entity.allow_sent_to.ToString();
                ddlAction.SelectedValue = entity.action_id.ToString();
                ddlStatus.SelectedValue = entity.status.ToString();
                ddlCollection.SelectedValue = entity.collection_id.ToString();
                txtMaxAdv.Text = entity.max_advertisment.ToString();
                txtSentAdv.Text = entity.sent_advertisment.ToString();

            }
            else
            {
                hdfAction.Value = "AddNew";
                hdfAdvId.Value = "-1";
                txtMessage.Text = string.Empty;
                ddlSenderName.SelectedIndex = 0;
                ddlMtFlag.SelectedIndex = 0;
                txtStartExpected.Text = string.Empty;
                txtEndExpected.Text = string.Empty;
                txtSentFrom.Text = string.Empty;
                txtSentTo.Text = string.Empty;
                ddlAction.SelectedIndex = 0;
                ddlStatus.SelectedIndex = 0;
                ddlCollection.SelectedIndex = 0;
                txtMaxAdv.Text = "0";
                txtSentAdv.Text = "0";
            }
        }

        protected void btnOK_Click(object sender, EventArgs e)
        {
            try
            {
                if (CheckFullInfo())
                {
                    //Set properties
                    Sami_SMS_CRM_Business.crm_advertisment entity = repository.GetById(int.Parse(hdfAdvId.Value)) ?? new Sami_SMS_CRM_Business.crm_advertisment();
                    entity.message = txtMessage.Text.Replace(Environment.NewLine, "\n");
                    entity.sender_name = ddlSenderName.SelectedValue;
                    entity.mt_flag = ddlMtFlag.SelectedValue;
                    entity.start_expected = DateTime.Parse(txtStartExpected.Text, DateTimeFormat);
                    entity.end_expected = DateTime.Parse(txtEndExpected.Text, DateTimeFormat);
                    entity.allow_sent_from = TimeSpan.Parse(txtSentFrom.Text);
                    entity.allow_sent_to = TimeSpan.Parse(txtSentTo.Text);
                    entity.action_id = int.Parse(ddlAction.SelectedValue);
                    entity.collection_id = int.Parse(ddlCollection.SelectedValue);
                    entity.status = ddlStatus.SelectedValue;
                    entity.max_advertisment = int.Parse(txtMaxAdv.Text);
                    entity.sent_advertisment = int.Parse(txtSentAdv.Text);
                    switch (hdfAction.Value)
                    {
                        case "Edit":
                            repository.Update(entity);
                            BindDataTable();
                            break;
                        case "AddNew":
                            entity.created_on = DateTime.Now;
                            entity.create_by = CurUser.UserName;
                            repository.AddNew(entity);
                            BindDataTable();
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                new LogRepository().InsertLog(ex);
            }
        }

        protected void btnAddNew_Click(object sender, ImageClickEventArgs e)
        {
            if (AllowManageAdvertisment())
            {
                SetDataAdv(null);
                ScriptManager.RegisterStartupScript(this, this.GetType(), "", "OpenDialog('dialog-form1');", true);
            }
        }

        private bool CheckFullInfo()
        {
            string errMsg = string.Empty;
            if (string.IsNullOrEmpty(txtMessage.Text.Trim()))
                errMsg = "Message not allow null";
            if (string.IsNullOrEmpty(txtStartExpected.Text.Trim()))
                errMsg = "Start expected not allow null";
            if (string.IsNullOrEmpty(txtEndExpected.Text.Trim()))
                errMsg = "End expected not allow null";
            if (string.IsNullOrEmpty(txtSentFrom.Text.Trim()))
                errMsg = "Allow sent from not allow null";
            if (string.IsNullOrEmpty(txtSentTo.Text.Trim()))
                errMsg = "Allow sent to not allow null";
            if (string.IsNullOrEmpty(txtMaxAdv.Text.Trim()))
                errMsg = "Max advertisment not allow null";
            if (string.IsNullOrEmpty(txtSentAdv.Text.Trim()))
                errMsg = "Sent advertisment not allow null";
            if (errMsg == string.Empty)
            {
                return true;
            }
            else
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "error", "alert(\"" + Server.HtmlDecode(errMsg) + "\"); OpenDialog('dialog-form1');", true);
                return false;
            }
        }

        protected void rptTable_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            try
            {
                foreach (RepeaterItem item in rptTable.Items)
                {
                    HtmlTableCell control = (HtmlTableCell)item.FindControl("td_action_id");
                    Literal ltr = (Literal)item.FindControl("ltractionId");
                    control.Attributes.Add("title", Enumerations.GetEnumDescription((ActionId)int.Parse(ltr.Text)));
                    HtmlTableCell td_message = (HtmlTableCell)item.FindControl("td_message");
                    HiddenField hdf = (HiddenField)item.FindControl("hdfcollectionid");
                    td_message.Attributes.Add("title", collectionRepository.GetById(int.Parse(hdf.Value)).collection_name);
                }
            }
            catch (Exception ex)
            {
                new LogRepository().InsertLog(ex);
            } 
        }

        [WebMethod]
        public static string[] GetTotalMtQueue(int advertisment_id)
        {
            return new AdvertismentRepository().GetTotalMtQueue(advertisment_id);
        }
    }
}